<template>
    <div class="position-map" :style="{ width: width }">
        <!-- <div class="search-container">
            <input v-model="searchWord" placeholder="请输入关键字进行搜索" style="width: 300px; margin-right: 16px; margin-bottom: 16px" @keyup.enter.native="handleSearch" />
            <button type="primary" size="small" @click="handleSearch">搜索</button>
        </div> -->
        <!--  ak="http://api.map.baidu.com/api?v=2.0&ak=j2sy6K7okugeW8CR00ACyKYXGnRWQGHL&callback=mapInit" -->
        <!-- :map-click="true" -->
        <baidu-map ref="mapRef" class="map1" :center="center" :zoom="zoom" @ready="handler" :scroll-wheel-zoom="true"
            @click="handleClick">
            <!-- 缩放控件 -->
            <bm-navigation v-if="isShowNavigation" anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <!-- 定位控件 -->
            <bm-geolocation ref="geolocationRef" v-show="isShowGeolocation" anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
                :showAddressBar="false" :autoLocation="true" @locationSuccess="locationSuccess"></bm-geolocation>
            <!-- 地区检索 -->
            <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false"
                @searchcomplete="handleSearchComplete"></bm-local-search>
            <!-- 地图容器 -->
            <bm-view class="map-container" :style="{ width: '100%', height: height }"></bm-view>
            <!-- 行政区划 -->
            <!-- <bm-boundary name="广州市" :strokeWeight="1" strokeColor="blue" fillColor="#027aff"></bm-boundary> -->
            <bm-boundary v-for="(item,i) in boundaryArr" :key="'boundary'+i" :name="item" :strokeWeight="1"
                strokeColor="blue" fillColor="#027aff" strokeStyle="dashed"></bm-boundary>

        </baidu-map>

        <!-- <button type="primary" style="margin-top: 16px" @click="confirmPosition">位置选好了，确定标注</button> -->
    </div>
</template>

<script>
    import {
        BaiduMap,
        BmNavigation,
        BmView,
        BmGeolocation,
        BmLocalSearch,
        BmBoundary
    } from 'vue-baidu-map'
    export default {
        name: 'positionMap',
        components: {
            BaiduMap,
            BmNavigation,
            BmView,
            BmGeolocation,
            BmLocalSearch,
            BmBoundary
        },
        props: {
            width: {
                type: String,
                default: () => '100%'
            },
            initialPosition: {
                type: Object,
                default () {
                    return {
                        lng: null,
                        lat: null
                        // lng: 113.12851219549718,
                        // lat: 23.02775875078891
                    }
                }
            },
            height: {
                type: String,
                default: '390px'
            },
            isShowControl: {
                type: Boolean,
                default: true
            },
            isShowNavigation: {
                type: Boolean,
                default: true
            },
            isShowGeolocation: {
                type: Boolean,
                default: true
            },
            nameArr: {
                type: Array,
                default: []
            },
            centerObj: {
                type: Object,
                default: {}
            },
            zoomNum: {
                type: Number,
                default: 5
            }
        },
        watch: {
            initialPosition: {
                deep: true,
                immediate: true,
                handler(val) {
                    if (val.lng) {
                        this.center = val
                    }
                }
            },
            nameArr: {
                deep: true,
                immediate: true,
                handler(val) {
                    if (val) {
                        this.boundaryArr = val
                        console.log(this.boundaryArr, 'this.boundaryArr')
                    }
                }
            },
            centerObj: {
                deep: true,
                immediate: true,
                handler(val) {
                    if (val) {
                        this.center = val
                    }
                }
            },
            zoomNum: {
                deep: true,
                immediate: true,
                handler(val) {
                    if (val) {
                        this.zoom = val
                        console.log(this.zoom, 'this.zoom')
                    }
                }
            }
        },
        data() {
            return {
                searchWord: '',
                keyword: '',
                center: {},
                zoom: 5, // 缩放等级 省-5  市-8  区-10  街道
                locData: {
                    longitude: '',
                    latitude: ''
                },
                mapInstance: null, // 地图实例
                BMap: null,
                boundaryArr: [], // 阴影区域

            }
        },
        methods: {
            confirmPosition() {
                this.$emit('confirm', this.locData)
            },
            handleSearchComplete(res) {
                if (!res) return
                const info = res.Kr[0]
                const address = info.address
                const {
                    lng,
                    lat
                } = info.point
                const myPoint = new this.BMap.Point(lng, lat)
                this.showLabelAndMaker(address, lng, lat, myPoint)
            },
            handleSearch() {
                if (!this.searchWord) return
                this.keyword = this.searchWord
            },
            getPositionFunc() {
                const geolocation = new this.BMap.Geolocation()
                geolocation.getCurrentPosition(
                    r => {
                        console.log(r, 'r - 初始获取当前位置')
                        this.$emit('getPosition', r.address)
                    }, {
                        enableHighAccuracy: true
                    }
                )
            },
            // 地图初始化
            handler({
                BMap,
                map
            }) {
                this.BMap = BMap
                const geolocation = new this.BMap.Geolocation()
                geolocation.getCurrentPosition(
                    r => {
                        console.log(r, 'r - 初始获取当前位置')
                        if (!this.center.lng) {
                            this.center = {
                                lng: r.longitude,
                                lat: r.latitude
                            } // 设置center属性值
                        }
                        console.log(this.center, 'this.center')
                    }, {
                        enableHighAccuracy: true
                    }
                )
                this.mapInstance = map

                // this.$emit('complete')
            },
            //根据名称搜索
            getPointByAddress(address) {
                // 创建地理编码实例
                const myGeo = new this.BMap.Geocoder();
                // 对地址进行地理编码
                myGeo.getPoint(address, (point) => {
                    if (point) {
                        console.log(point, '根据名称搜索返回数据')
                        // 地理编码成功，返回经纬度坐标对象
                        let p = {
                            lng: point.lng,
                            lat: point.lat
                        }
                        this.center = p
                        this.showLabelAndMaker(address, point.lng, point.lat, p)
                        // this.boundaryArr = [address]
                        //  resolve(point);
                    } else {
                        // 地理编码失败
                        console.log('地理编码失败');
                    }
                }, '全国');
            },
            // 点击地图
            handleClick(e) {
                console.log(e, 'e - 点击地图', e.currentTarget.eh)
                setTimeout(() => {
                    const {
                        lng,
                        lat
                    } = e.point

                    const pt = new BMap.Point(e.point.lng, e.point.lat); //获取点击的经纬度点
                    const gc = new BMap.Geocoder(); // 创建地理编码实例
                    gc.getLocation(pt, (rs) => { // 根据点击的点获取地址信息
                        console.log(rs, 'rs - 根据点击的点获取地址信息')
                        // 显示行政区名称 省/province - 市/city - 区/district
                        // for (let k of this.boundaryArr) {
                        //     if (rs.addressComponents.province.includes(k) || rs.addressComponents
                        //         .city == k ||
                        //         rs.addressComponents.district == k) {
                        //         let obj = rs.addressComponents
                        //         obj.name = k
                        //         this.$emit('mapClick', obj)
                        //     }
                        // }
                        this.$emit('mapClick', rs.addressComponents)
                    });

                }, 1000);
            },
            // 显示标记点和位置信息标签
            showLabelAndMaker(address, lng, lat, point) {
                console.log(address, lng, lat, point, 'sdad')
                this.mapInstance.clearOverlays()
                const myLabel = new this.BMap.Label(address, {
                    position: point
                }) // 百度地图文档https://lbsyun.baidu.com/cms/jsapi/reference/jsapi_reference.html#a3b9
                const content = `
                    <div style="margin-bottom:16px">坐标: ${lng}, ${lat}</div>
                    <div>地址: ${address}</div>
                `
                myLabel.setStyle({
                    fontSize: '14px',
                    color: 'black',
                    backgroundColor: '#cccccc',
                    padding: '8px'
                })
                myLabel.setContent(content)
                this.mapInstance.addOverlay(myLabel)

                const myMarker = new this.BMap.Marker(point)
                this.mapInstance.addOverlay(myMarker)
            },

            // 定位成功回调
            locationSuccess(point) {
                console.log(point, '点击获取定位', point.addressComponent)
                const address = `${point.addressComponent.province}${point.addressComponent.city}`
                const {
                    lng,
                    lat
                } = point.point
                const myPoint = new this.BMap.Point(lng, lat)
                // this.showLabelAndMaker(address, lng, lat, myPoint)
                this.locData.longitude = lng
                this.locData.latitude = lat

                var gc = new BMap.Geocoder();
                gc.getLocation(myPoint, (rs) => {
                    var addComp = rs.addressComponents;
                    // console.log('国家：', addComp.country);
                    // console.log('省：', addComp.province);
                    // console.log('市：', addComp.city);
                    console.log('区：', addComp.district); // 这里可以获取到区或县信息
                    // console.log('街道：', addComp.street);
                    // console.log('街道号码：', addComp.streetNumber);
                    this.$emit('locationSuccess', addComp.district)
                });

                // this.boundaryArr = [point.addressComponent.district]
                // this.$emit('locationSuccess',)
                this.zoom = 10
            },
            // 检索
            localSearch(keyword) {
                const map = this.mapInstance
                const centerPoint = this.center
                return new Promise((resolve, reject) => {
                    const local = new this.BMap.LocalSearch(this.mapInstance, {
                        renderOptions: {
                            map: this.mapInstance,
                            autoViewport: false
                        },
                        onSearchComplete: function(results) {
                            // console.log('==========')
                            // console.log(results)

                            results.as = results.as.map(v => {
                                let dis = map.getDistance(v.point, centerPoint)
                                let strDis = ''
                                if (dis > 1000) {
                                    strDis = (dis / 1000).toFixed(1) + 'km'
                                } else {
                                    strDis = dis.toFixed(0) + 'm'
                                }

                                return {
                                    ...v,
                                    dis: strDis,
                                    disNum: dis
                                }
                            }).sort((a, b) => a.disNum - b.disNum)
                            resolve(results)
                        }
                    });

                    const {
                        lng,
                        lat
                    } = this.center
                    const myPoint = new this.BMap.Point(lng, lat)
                    local.searchNearby(keyword, myPoint, 3000);
                })
            },
            // 计算方位
            getDirDescription(pt1, pt2) {
                var h = pt1.lng - pt2.lng;
                var v = pt1.lat - pt2.lat;
                if (Math.abs(h) > Math.abs(v)) {
                    return h < 0 ? "西" : "东";
                } else {
                    return v < 0 ? "南" : "北";
                }
            },
            siteClick() {
                console.log('点击返回城市', 'siteClick')
            },
        }
    }
</script>
<style lang="less" scoped>
    .position-map {
        width: 90vw;
        height: 400px;
        text-align: center;
    }

    .search-container {
        text-align: left;
    }

    ::v-deep {
        .anchorBL {
            display: none;
        }
    }
</style>
